﻿using System;
using System.Threading;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using KPFramework.Base;
using KPFramework.Extensions;
using KPFramework.KUIFrame;

namespace KPFramework.Demo
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            bool createNew;
            using (Mutex mutex = new Mutex(true, Application.ProductName, out createNew))
            {
                if (createNew)
                {
                    BindExceptionHandler();//全局异常处理
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    DevExpress.Skins.SkinManager.EnableFormSkins();
                    //DevExpress.UserSkins.BonusSkins.Register();
                    try
                    {
                        SetDevTheme();//设置Dev主题

                        MainUi.MainUi.ShowSplashScreen();

                        var app = KApplication.GetApp();
                        app.Name = "YxAppFrame";
                        app.SetValue("PN", "11D315E8-B528-40EC-A40B-D686A07683AD");
                        if (KApplication.GetApp().Start() != Base.RetValue.RET_SUC)
                        {
                            MessageBox.Show(@"插件系统启动失败.详细错误信息已经输入到日志文件中.");
                            return;
                        }

                        var mainUi = CreateMainWnd();
                        if (mainUi == null)
                        {
                            MessageBox.Show(@"未能正确创建插件主框架!", @"系统异常", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            return;
                        }
                        Application.Run(mainUi);
                    }
                    finally
                    {
                        //系统停止，退出插件系统
                        KApplication.GetApp().Stop();
                        System.Environment.Exit(1);
                    }
                }
                else
                {
                    MessageBox.Show(@"应用程序已经在运行中........", @"提示", MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    Thread.Sleep(1000);

                    //  终止此进程并为基础操作系统提供指定的退出代码。
                    Environment.Exit(1);
                }
               
            }
           

        }


        #region UI组件显示
        /// <summary>
        /// 创建主框架
        /// </summary>
        /// <returns></returns>
        private static Form CreateMainWnd()
        {
            //UIFrame.Frame对象，全局唯一对象，可以从配置重动态创建Frame框架组件
            //在本案例中，直接new MainUi作为全局的Frame组件框架.
            //var frame = UIFrame.Frame;
            var uiFrame = new MainUi.MainUi(UIFrame.Frame);
            Form mainForm = uiFrame.GetOrCreateCtrl<Form>();
            uiFrame.ShowFrame();
            return mainForm;
        }

        /// <summary>
        /// 初始化设置对象UI主题
        /// </summary>
        private static void SetDevTheme()
        {
            string strDefaultName =Config.KConfigCenter.GetAppSettingValue("Skin");
            string strDefaultPalette = Config.KConfigCenter.GetAppSettingValue("PaletteName");
            if (string.IsNullOrEmpty(strDefaultName))
            {
                strDefaultName = "The Bezier";
               Config.KConfigCenter.SetAppSettingValue("Skin", strDefaultName);
            }
            if (string.IsNullOrEmpty(strDefaultPalette))
            {
                strDefaultPalette = "Office Colorful";
                Config.KConfigCenter.SetAppSettingValue("PaletteName", strDefaultPalette);
            }
            UserLookAndFeel.Default.SetSkinStyle(strDefaultName, strDefaultPalette);
            UserLookAndFeel.Default.StyleChanged += Default_StyleChanged;
        }

        private static void Default_StyleChanged(object sender, EventArgs e)
        {
            string strName = DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSkinName;
            Config.KConfigCenter.SetAppSettingValue("Skin", strName);
            string strPallter = DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSvgPaletteName;
            if (string.IsNullOrEmpty(strPallter) && strName == "The Bezier")
            {
                string strDefaultPalette = Config.KConfigCenter.GetAppSettingValue("PaletteName");
                if (string.IsNullOrEmpty(strDefaultPalette))
                {
                    strDefaultPalette = "Office Colorful";
                   Config.KConfigCenter.SetAppSettingValue("PaletteName", strDefaultPalette);
                }
                DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(strName, strDefaultPalette);
            }
            else
                Config.KConfigCenter.SetAppSettingValue("PaletteName", strPallter);
        }
        #endregion 


        #region 异常处理

        /// <summary>
        /// 绑定程序中的异常处理
        /// </summary>
        private static void BindExceptionHandler()
        {
            //设置应用程序处理异常方式：ThreadException处理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += Application_ThreadException;
            //处理未捕获的异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
        /// <summary>
        /// 处理UI线程异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string strMsg = e.Exception.FormatMessage();
            //记录日志
            KApplication.ErrorLog(e.Exception.Message, "Application", Common.App);
            MessageBox.Show(strMsg, @"系统异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        /// <summary>
        /// 处理未捕获的异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string strMsg = e.ToString();
            //记录日志
            KApplication.ErrorLog(strMsg, "Application", Common.App);
            MessageBox.Show(strMsg, @"系统异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        #endregion 
    }
}
